package com.homepig.mongodb;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.BsonType;
import org.bson.Document;

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.exists;
import static com.mongodb.client.model.Filters.type;
import static java.util.Arrays.asList;

/**
 * 查询空字段或缺少字段
 * @author fengchao
 */
public class QueryNullFields {
    private static MongoCollection mongoCollection;

    static {
        MongoClient mongoClient = new MongoClient("localhost",27017);
        MongoDatabase mongoDatabase = mongoClient.getDatabase("mongo_stu");
        mongoCollection = mongoDatabase.getCollection("inventory");

        mongoCollection.drop();

        mongoCollection.insertMany(asList(
                Document.parse("{'_id': 1, 'item': null}"),
                Document.parse("{'_id': 2}")
        ));
    }

    /**
     * 查询item字段存在且为null，或item字段不存在的记录
     * @param mongoCollection
     */
    public void equalityFilter(MongoCollection mongoCollection){
        FindIterable findIterable = mongoCollection.find(eq("item",null));
        MongoCursor mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()){
            Document document = (Document) mongoCursor.next();
            System.out.println(document.toJson());
        }
    }

    /**
     * 查询item字段存在，且值为null的记录
     * @param mongoCollection
     */
    public void typeCheck(MongoCollection mongoCollection){
        FindIterable findIterable = mongoCollection.find(type("item", BsonType.NULL));
        MongoCursor cursor = findIterable.iterator();
        while (cursor.hasNext()){
            Document document = (Document) cursor.next();
            System.out.println(document.toJson());
        }
    }

    /**
     * 查询item字段存在或不存在的记录
     * @param mongoCollection
     */
    public void existenceCheck(MongoCollection mongoCollection){
        FindIterable findIterable = mongoCollection.find(exists("item", false));
        MongoCursor mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()){
            Document document = (Document) mongoCursor.next();
            System.out.println(document.toJson());
        }
    }

    public static void main(String[] args) {
        QueryNullFields queryNullFields = new QueryNullFields();
        queryNullFields.equalityFilter(mongoCollection);
        queryNullFields.typeCheck(mongoCollection);
        queryNullFields.existenceCheck(mongoCollection);
    }
}
